package gui;

import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JViewport;

@SuppressWarnings("serial")
public class MapViewPort extends JViewport {
	private int speed = 20;
	
	public MapViewPort(){
		this.setFocusable(true);
		this.addKeyListener(new ArrowListener());
	}
	
	public MapViewPort(LayeredPane mp){
		this.setFocusable(true);
		this.addKeyListener(new ArrowListener());
		this.setView(mp);
	}
	
	// sets the horizontal and vertical scrolling speed
	public void setSpeed(int speed){
		if(speed > 0){
			this.speed = speed;
		}
	}
	
	// returns the scrolling speed
	public int getSpeed(){
		return this.speed;
	}
	
	// listener for the arrow keys
	private class ArrowListener extends KeyAdapter {
		private int x1, y1, x2, y2;
		
		public void keyPressed(KeyEvent k){
			int code = k.getKeyCode();
			Point p = getViewPosition();

			switch(code){
			case KeyEvent.VK_RIGHT 	:
				x1 = p.x + speed;
				x2 = getViewSize().width - getSize().width;
								
				if(x1 < x2){
					setViewPosition(new Point(x1, p.y));
				} else {
					setViewPosition(new Point(x2, p.y));
				}
				
				break;
			case KeyEvent.VK_UP 	:
				y1 = p.y - speed;
				
				if(y1 > 0){
					setViewPosition(new Point(p.x, y1));
				} else {
					setViewPosition(new Point(p.x, 0));
				}
				
				break;
			case KeyEvent.VK_LEFT	:
				x1 = p.x - speed;
				
				if(x1 > 0){
					setViewPosition(new Point(x1, p.y));
				} else {
					setViewPosition(new Point(0, p.y));
				}
				
				break;
			case KeyEvent.VK_DOWN	:
				y1 = p.y + speed;
				y2 = getViewSize().height - getSize().height;
				
				if(y1 < y2){
					setViewPosition(new Point(p.x, y1));
				} else {
					setViewPosition(new Point(p.x, y2));
				}
			
				break;
			}
		}
	}
}